<?php

$di = \application\units\Di::getInstance();

$params = [
    'admin_id' => $di->auth->id,
    'id'       => explode(',', (string)$di->request->params('id')),
];

$authRoleIds = [];
if ($params['admin_id']) {
    $adminIds    = $di->auth->getChildrenRoleAdminIds($params['admin_id'], true);
    $authRoleIds = $di->auth->getRoleIdsByAdminId($params['admin_id']);
} else {
    $adminIds = [$params['admin_id']];
}

if (array_diff($params['id'], $adminIds)) {
    throw new LogicException('不能操作其他角色组的用户');
}

$has = $di->db->find('select a.admin_id,g.* from admin_role_access a
            join admin_role g on g.id=a.role_id
            where admin_id in (:admin_id) and a.role_id in (:role_id)', [
    'admin_id' => $params['id'],
    'role_id'  => $authRoleIds,
], PDO::FETCH_GROUP | PDO::FETCH_ASSOC);

if ($has) {
    throw new LogicException('不能删除跟自己相同角色的管理员');
}

$rows = $di->db->find('select * from admin where id in (:id)', [
    'id' => $params['id'],
]);

if (!$rows) throw new LogicException('未找到记录');

try {
    
    $di->db->beginTransaction();
    // 删除管理员
    $stat = $di->db->execute('delete from admin where id in (:id)', [
        'id' => $params['id'],
    ]);
    
    if ($stat->rowCount() <= 0) throw new PDOException('操作失败');
    
    // 删除管理员角色组
    $stat = $di->db->execute('delete from admin_role_access where admin_id in (:admin_id)', [
        'admin_id' => $params['id'],
    ]);
    
    if ($stat->rowCount() <= 0) throw new PDOException('操作失败');
    
    $di->db->commit();
} catch (Exception $e) {
    $di->db->rollback();
    throw $e;
}

return [];